require 'zdc.doc'
require 'zsvc.que'
require 'zsvc.packet'
require 'zsvc.evhandle'
local monutil=require 'zsvc.monutil'

local remove=table.remove
module(..., package.seeall)

local Notifycon= {}
zsvc.evhandle.InitEvent(Notifycon)
local Notifycon_mt = {__metatable = {}, __index = Notifycon}


function new(params)
	local obj = setmetatable({mon=params.mon,proxyaddr=params.proxyaddr,react=params.react,notifys=params.notifys,logger=params.logger,que=zsvc.que.new(),sp=zsvc.packet.new(),rp=zsvc.packet.new()}, Notifycon_mt)
	obj.name='Notifycon'
	obj.authed=false
	obj:OnClose()
	return obj
end

function Notifycon:SendNotify(appid,ch,info)
	local np=zsvc.packet.new()
	np:SetMsg(appid,ch,info)
	self:SendPacket(np)
end

function Notifycon:cb_conn_ready()
	self.connwait=false
	self.logger:info('Notifycon has connect to ' .. logging.tostring(self.proxyaddr))
	monutil.mon_start(self)
	self.notifys:AddOne(self.proxyaddr.ik,self)
end

function Notifycon:OnClose()
	self.que:Clear() --TODO: reconnected and send left pkt
	if self.fd then
		self:_bv_close()
		self.logger:warn('Notifycon close fd for ' .. logging.tostring(self.proxyaddr))
		monutil.mon_broke(self)
		self.fd:close()
		self.fd=nil
	end
	self.connwait=nil
	self.notifys:DelOne(self.proxyaddr.ik,self)
	self:_bv_init_connect(self.proxyaddr.host,self.proxyaddr.port)
end

function Notifycon:OnMsg(packet)
	do
		self.logger:error("Notifycon should not recv any info")
		return
	end
	local h=packet:ParseHeader()
	local pos,ch=packet:GetCH()
	local cli=ch.accid
	local clip=ch.path and ch.path[#ch.path]
	if cli then
		local clifd=self.clis:Find(cli,clip)
		if clifd then
			local np=zsvc.packet.new()
			remove(ch.path)
			np:SetMsg2(h.appid,ch,packet.buf,pos)
			clifd:SendPacket(np)
			return
		end
		self.logger:error("Notifycon can't find client " .. cli)
		return
	end
	self.logger:error("Notifycon recv a bad msg from app, no path")
	return
end

